package acceso.listener;

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail {

    public static void enviarMensajeMail(String to, String cc, String cco, String from, String host, String subject, String msgText, String ti_content, String il_adjunt, String co_adjunt, String no_adjunt, String il_compre)
            throws Exception {
        System.out.println("--------------------------------------------------------------------");
        System.out.println("ENTRO A ENVIAR MENSAJE MAIL acceso----------------------------------");
        System.out.println("--------------------------------------------------------------------");

        boolean debug = Boolean.valueOf("true").booleanValue();
        if (Texto.isNull(to)) {
            throw new Exception("Falta especificar  e-mail de destinatario ");
        }
        if (Texto.isNull(from)) {
            throw new Exception("Falta especificar e-mail de remitente");
        }
        if (Texto.isNull(host)) {
            throw new Exception("Falta especificar servidor e-mail");
        }
        if (Texto.isNull(subject)) {
            throw new Exception("Falta especificar t�tulo de mensaje de e-mail");
        }
        if (Texto.isNull(msgText)) {
            throw new Exception("Falta especificar contenido de mensaje de e-mail");
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", "192.168.2.102");
        props.put("mail.smtp.localhost", "192.168.2.101");

        if (debug) {
            props.put("mail.debug", "true");
        }

        Session session = Session.getInstance(props, null);
        session.setDebug(debug);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));

            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart bp = new MimeBodyPart();

            if ((il_adjunt != null) && (il_adjunt.equals("S"))) {
                DataHandler dh = null;
                new ConsultasMail();
                ConsultasMail.consultaArchivo(co_adjunt, no_adjunt, il_compre);

                if (il_compre.equals("S")) {
                    dh = new DataHandler(new FileDataSource("/tmp/archivotemp.zip"));
                    if (co_adjunt.lastIndexOf('.') != -1) {
                        co_adjunt = co_adjunt.substring(0, co_adjunt.lastIndexOf('.'));
                    }
                    co_adjunt = co_adjunt + ".zip";
                } else {
                    dh = new DataHandler(new FileDataSource("/tmp/archivotemp.txt"));
                }
                bp.setDataHandler(dh);
                bp.setFileName(co_adjunt);
                mp.addBodyPart(bp);
            }

            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

            if ((cc != null) && (!cc.equals(""))) {
                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
            }

            if ((cco != null) && (!cco.equals(""))) {
                msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(cco, false));
            }

            msg.setSubject(subject);

            msg.setSentDate(new Date());

            bp = new MimeBodyPart();
            if ((ti_content != null) && (ti_content.equals("TH"))) {
                bp.setContent(msgText, "text/html");
            } else {
                bp.setContent(msgText, "text/plain");
            }
            mp.addBodyPart(bp);
            msg.setContent(mp);

            Transport.send(msg);
        } catch (MessagingException mex) {
            System.out.println("\n--Exception handling in Mail.java");

            mex.printStackTrace();
            System.out.println();
            Exception ex = mex;

            if ((ex instanceof SendFailedException)) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++) {
                            System.out.println("         " + invalid[i]);
                        }
                    }
                    throw new Exception("    ** Invalid Addresses");
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++) {
                            System.out.println("         " + validUnsent[i]);
                        }
                    }
                    throw new Exception("    ** ValidUnsent Addresses");
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++) {
                            System.out.println("         " + validSent[i]);
                        }
                    }
                    throw new Exception("    ** ValidSent Addresses");
                }
            }
            throw new Exception("    ** Excepcion desconocida");
        }
    }

    public static void enviarMensajeMail(String to, String cc, String cco, String from, String host, String subject, String msgText, String ti_content, String il_adjunt, String co_adjunt, String no_adjunt, String il_compre, String no_respon) throws Exception {
        System.out.println("--------------------------------------------------------------------");
        System.out.println("ENTRO A ENVIAR MENSAJE MAIL server: " + host + "-------------------- ");
        System.out.println("--------------------------------------------------------------------");

        boolean debug = Boolean.valueOf("true").booleanValue();
        if (Texto.isNull(to)) {
            throw new Exception("Falta especificar  e-mail de destinatario ");
        }
        if (Texto.isNull(from)) {
            throw new Exception("Falta especificar e-mail de remitente");
        }
        if (Texto.isNull(host)) {
            throw new Exception("Falta especificar servidor e-mail");
        }
        if (Texto.isNull(subject)) {
            throw new Exception("Falta especificar t�tulo de mensaje de e-mail");
        }
        if (Texto.isNull(msgText)) {
            throw new Exception("Falta especificar contenido de mensaje de e-mail");
        }

        Properties props = new Properties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.localhost", "192.168.2.101");

        if (debug) {
            props.put("mail.debug", "true");
        }

        Session session = Session.getInstance(props, null);
        session.setDebug(debug);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));

            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart bp = new MimeBodyPart();

            if ((il_adjunt != null) && (il_adjunt.equals("S"))) {
                DataHandler dh = null;
                new ConsultasMail();
                ConsultasMail.consultaArchivo(co_adjunt, no_adjunt, il_compre);

                if (il_compre.equals("S")) {
                    dh = new DataHandler(new FileDataSource("/tmp/archivotemp.zip"));
                    if (co_adjunt.lastIndexOf('.') != -1) {
                        co_adjunt = co_adjunt.substring(0, co_adjunt.lastIndexOf('.'));
                    }
                    co_adjunt = co_adjunt + ".zip";
                } else {
                    dh = new DataHandler(new FileDataSource("/tmp/archivotemp.txt"));
                }
                bp.setDataHandler(dh);
                bp.setFileName(co_adjunt);
                mp.addBodyPart(bp);
            }

            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

            if ((cc != null) && (!cc.equals(""))) {
                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
            }

            if ((cco != null) && (!cco.equals(""))) {
                msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(cco, false));
            }

            if ((no_respon != null) && (!no_respon.equals(""))) {
                msg.setReplyTo(new InternetAddress[]{new InternetAddress(no_respon)});
            }

            msg.setSubject(subject);

            msg.setSentDate(new Date());

            bp = new MimeBodyPart();
            if ((ti_content != null) && (ti_content.equals("TH"))) {
                bp.setContent(msgText, "text/html");
            } else {
                bp.setContent(msgText, "text/plain");
            }
            mp.addBodyPart(bp);
            msg.setContent(mp);

            Transport.send(msg);
        } catch (MessagingException mex) {
            System.out.println("\n--Exception handling in Mail.java");

            mex.printStackTrace();
            System.out.println();
            Exception ex = mex;

            if ((ex instanceof SendFailedException)) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++) {
                            System.out.println("         " + invalid[i]);
                        }
                    }
                    throw new Exception("    ** Invalid Addresses");
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++) {
                            System.out.println("         " + validUnsent[i]);
                        }
                    }
                    throw new Exception("    ** ValidUnsent Addresses");
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++) {
                            System.out.println("         " + validSent[i]);
                        }
                    }
                    throw new Exception("    ** ValidSent Addresses");
                }
            }
            throw new Exception("    ** Excepcion desconocida");
        }
    }

    private static void usage() {
        System.out.println("usage: java msgsendsample <to> <from> <smtp> true|false");
    }
}
